package ranks.types.mappings;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import ranks.tools.parser.HTMLParser;
import ranks.types.Player;

public abstract class PlayerMapping {
	
	protected URL[] dataURLs;
	protected String startPhrase;
	protected String endPhrase;
	protected String parseCharacter;
	protected Map<String, String> removePhrases;
	protected List<String> invalidPhrases;

	protected abstract void setUpVariables();
	protected abstract boolean isDataValid(String data);
	protected abstract Player createPlayer(String data);
	
	public void loadPlayers() {
		HTMLParser parser
			= new HTMLParser(startPhrase,
							 endPhrase,
							 removePhrases);
		
		for(URL dataURL : this.dataURLs) { 
			String parsedData = parser.parseURL(dataURL);
		
		List<Player> players = this.loadPlayersFromData(parsedData);
		
		this.updatePlayerMap(players);

		}
		
	}
	
	private List<Player> loadPlayersFromData(String dataIn) {

		List<Player> players = new ArrayList<Player>();
		
		String[] splitData = dataIn.split("\n");
		
		for(String data : splitData) {
			if(isDataValid(data)) {
				Player player = createPlayer(data);
				players.add(player);
			}
		}
		
		return players;
	}
	
	private void updatePlayerMap(List<Player> players) {
		for(Player player : players) {
			String playerKey = player.getPlayerKey();
			Player tempPlayer = Player.ALL_PLAYERS.get(playerKey);
			if(tempPlayer != null) {
				for(Map.Entry<String, Integer> rank : tempPlayer.getAllRankings().entrySet()) {
					player.setRanking(rank.getKey(), rank.getValue());
				}
			}
			
			Player.ALL_PLAYERS.put(playerKey, player);
		}
	}

	public URL[] getDataURLs() {
		return dataURLs;
	}

	public String getStartPhrase() {
		return startPhrase;
	}

	public String getEndPhrase() {
		return endPhrase;
	}

	public String getParseCharacter() {
		return parseCharacter;
	}

	public Map<String, String> getRemovePhrases() {
		return removePhrases;
	}
}
